'use strict';

const db = uniCloud.database();
const _ = db.command;
const collection = db.collection('wallpapers');

exports.main = async (event, context) => {
  try {
    // 验证管理员权限
    const { OPENID } = context;
    const adminInfo = await db.collection('admin_users')
      .where({
        openid: OPENID,
        status: 1
      })
      .get();
    
    // if (adminInfo.data.length === 0) {
    //   return {
    //     code: 401,
    //     message: '无管理员权限'
    //   };
    // }
    
    // 获取参数
    const {
      keyword = '',
      categoryId = '',
      page = 1,
      pageSize = 20,
      orderBy = 'createTime',
      sort = 'desc',
      status = ''
    } = event;
    
    // 构建查询条件
    const query = {};
    
    // 添加关键词搜索条件
    if (keyword.trim()) {
      const keywordRegex = new RegExp(keyword.trim());
      query.$or = [
        { title: db.RegExp({regexp: keyword, options: 'i'}) },
        { description: db.RegExp({regexp: keyword, options: 'i'}) },
        { tags: _.elemMatch(_.regexp(keyword, 'i')) }
      ];
    }
    
    // 添加分类筛选条件
    if (categoryId) {
      query.categoryId = categoryId;
    }
    
    // 添加状态筛选条件
    if (status !== '') {
      query.status = status === 'active' ? 1 : 0;
    }
    
    // 计算总数
    const totalResult = await collection.where(query).count();
    const total = totalResult.total;
    
    // 计算偏移量
    const skip = (page - 1) * pageSize;
    
    // 查询数据
    const wallpapersRes = await collection
      .where(query)
      .orderBy(orderBy, sort)
      .skip(skip)
      .limit(pageSize)
      .get();
    
    // 补充分类信息
    const wallpapers = wallpapersRes.data;
    let wallpapersWithCategory = wallpapers;
    
    if (wallpapers.length > 0) {
      // 获取所有分类ID
      const categoryIds = [...new Set(wallpapers.map(w => w.categoryId).filter(Boolean))];
      
      if (categoryIds.length > 0) {
        // 批量查询分类信息
        const categories = await db.collection('categories')
          .where({
            _id: _.in(categoryIds)
          })
          .get();
        
        // 构建分类映射
        const categoryMap = {};
        categories.data.forEach(cat => {
          categoryMap[cat._id] = cat;
        });
        
        // 为每个壁纸补充分类名称
        wallpapersWithCategory = wallpapers.map(wallpaper => {
          if (wallpaper.categoryId && categoryMap[wallpaper.categoryId]) {
            return {
              ...wallpaper,
              categoryName: categoryMap[wallpaper.categoryId].name
            };
          }
          return wallpaper;
        });
      }
    }
    
    // 记录操作日志
    await db.collection('admin_logs').add({
      adminId: adminInfo.data[0]?._id || 'unknown',
      adminName: adminInfo.data[0]?.username || 'unknown',
      action: 'getWallpapers',
      params: {
        keyword,
        categoryId,
        page,
        pageSize,
        status
      },
      success: true,
      createTime: new Date()
    });
    
    return {
      code: 0,
      message: '获取壁纸列表成功',
      data: wallpapersWithCategory,
      total: total,
      page: page,
      pageSize: pageSize,
      totalPages: Math.ceil(total / pageSize)
    };
  } catch (error) {
    console.error('获取壁纸列表失败:', error);
    
    // 记录错误日志
    try {
      await db.collection('admin_logs').add({
        action: 'getWallpapers',
        params: event,
        success: false,
        error: error.message,
        createTime: new Date()
      });
    } catch (logError) {
      console.error('记录错误日志失败:', logError);
    }
    
    return {
      code: 500,
      message: '获取壁纸列表失败，请稍后重试',
      error: error.message
    };
  }
};